package bysun.weather.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * HTTP request
 */
public class HTTPRequester {

    public static String post(String url){
        return  post(url, Collections.<String, Object>emptyMap());
    }

    public static String post(String url,Map<String,Object> params){
        HttpClient client = ConnectionManager.getHttpClient();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
        }
        String result = "";
        try {
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(uefEntity);
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return  result;
    }

    public static String get(String url){
        HttpClient client = ConnectionManager.getHttpClient();
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return  result;
    }
}
